package servlet;

import model.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "changeUserPassword", urlPatterns = "/changeUserPassword")
public class ChangeUserPasswordServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user_login.jsp");
            return;
        }

        // 获取表单数据
        String originalPassword = request.getParameter("originalPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmNewPassword = request.getParameter("confirmNewPassword");

        // 验证数据
        if (originalPassword == null || newPassword == null || confirmNewPassword == null ||
            originalPassword.trim().isEmpty() || newPassword.trim().isEmpty() || confirmNewPassword.trim().isEmpty()) {
            request.setAttribute("msg", "请填写完整的密码信息！");
            request.getRequestDispatcher("/user_center.jsp").forward(request, response);
            return;
        }

        // 验证新密码与确认密码是否一致
        if (!newPassword.equals(confirmNewPassword)) {
            request.setAttribute("msg", "新密码与确认密码不一致！");
            request.getRequestDispatcher("/user_center.jsp").forward(request, response);
            return;
        }

        // 验证原密码是否正确
        if (!userService.verifyPassword(user.getId(), originalPassword)) {
            request.setAttribute("msg", "原密码不正确！");
            request.getRequestDispatcher("/user_center.jsp").forward(request, response);
            return;
        }

        // 更新密码
        user.setPassword(newPassword);
        boolean isSuccess = userService.updatePassword(user.getId(), newPassword);
        
        if (isSuccess) {
            request.setAttribute("msg", "密码修改成功！");
        } else {
            request.setAttribute("msg", "密码修改失败，请重试！");
        }

        request.getRequestDispatcher("/user_center.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
} 